﻿using PetaPoco;
using YMJF_Service.Models;
using YMJF_Service.Common;
using YMJF_Service.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using Newtonsoft.Json.Linq;
using YMJF_Service.Service;
using xrwang.weixin.PublicAccount;
using System.Configuration;
using HMACAuthentication.WebApi.Filters;

namespace YMJF_Service.Controllers
{
    /// <summary>
    /// 账户管理
    /// </summary>
    [RoutePrefix("api/account")]

    public class AccountController : ApiController
    {
        ConnectionStringMySQLDB db = new ConnectionStringMySQLDB();
        MemoryCacher mc = new MemoryCacher();

        private static string salt = AccountSrv.salt;
        
        /// <summary>
        /// 用户登录
        /// </summary>
        /// <param name="accModel">登录表单</param>
        /// <returns></returns>
        [HttpPost]
        [Route("login")]
        public ApiResult Login([FromBody]account accModel)
        {                 
            ApiResult res = new ApiResult();         
            try
            {
                string account = accModel.Account;
                string Pwd = AccountSrv.MD5Encrypt(accModel.Pwd);           
                string token = Guid.NewGuid().ToString();
                string sql = string.Format("select ID,Account,Name,'" + token + "' as token  from Account where  SysDeleted = 0 and  Account='{0}' and  Pwd='{1}'", account, Pwd);
                object acc = db.SingleOrDefault<object>(sql);
                if (acc != null)
                {
                    res.code = HttpCode.success;
                    res.message = token;
                    //res.message = "登录成功";
                    res.data = acc;
                    mc.Add(token, accModel.Account);//保存用户token
                }
                else
                {
                    string sql2 = string.Format("select * from Account where Account='{0}'", account);
                    if (db.Fetch<object>(sql2).Count > 0)
                    {
                        res.code = HttpCode.code102;
                        res.message = "密码错误";
                    }
                    else
                    {
                        res.code = HttpCode.code101;
                        res.message = "用户名不存在";
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBL.Insert(new MessageBL("account", "用户登录错误：" + ex.Message));
                res.code = HttpCode.fail;
                res.message = ex.Message;
            }
            return res;
        }

        public class PwdModel
        {
             public string ID { get; set; }
		     public string Pwd { get; set; }
		     public string NewPwd { get; set; }
        }

       /// <summary>
        /// 修改密码
       /// </summary>
       /// <param name="pwdModel">修改密码实体</param>
       /// <returns></returns>
        [HttpPost]
        [Route("UpdatePwd")]
        [HMACAuthenticationAttribute]
        public ApiResult UpdatePwd([FromBody]PwdModel pwdModel)
        { //[FromBody]
            ApiResult res = new ApiResult();
            try
            {
                string user = "admin";
                string ID = pwdModel.ID;
                string Pwd = AccountSrv.MD5Encrypt(pwdModel.Pwd);
                string NewPwd = AccountSrv.MD5Encrypt(pwdModel.NewPwd);
                string sql = string.Format("select * from Account where ID='{0}' and Pwd='{1}'", ID, Pwd);
                account acc = db.SingleOrDefault<account>(sql);
                if (acc != null)
                {
                    int obj = account.Update(string.Format(" set SysLastUpd = '{1}',SysLastUpdBy = '{2}',Pwd = '{3}' where ID = '{0}' ", ID, DateTime.Now, user, NewPwd));
                    if (obj > 0)
                    {
                        res.code = HttpCode.success;
                        res.message = "修改密码成功";
                    }
                    else
                    {
                        res.code = HttpCode.Mod_Failed;
                        res.message = "修改密码失败";
                    }

                }
                else
                {
                        res.code = HttpCode.code102;
                        res.message = "原密码不正确";                  
                }
            }
            catch (Exception ex)
            {
                MessageBL.Insert(new MessageBL("account", "修改密码错误：" + ex.Message));
                res.code = HttpCode.fail;
                res.message = ex.Message;
            }
            return res;
        }

       /// <summary>
        /// 添加账户
       /// </summary>
       /// <param name="resObj">账户对象</param>
       /// <returns></returns>
        [HttpPost]
        [Route("add")]
        [HMACAuthenticationAttribute]
        public ApiResult AddAccount(dynamic resObj)
        {  //JObject
            ApiResult res = new ApiResult();
            try
            {
                string user = "admin";
                account data = new account();               
                data.ID = Guid.NewGuid().ToString();
                data.Account = resObj.Account; // obj["Account"].toString();
                data.Pwd = AccountSrv.MD5Encrypt(resObj.Pwd);
                data.Name = resObj.UserName;
                data.State = "1";//1启用0不启用
                data.SysOrder = 9999;
                data.SysCreatedBy = user;
                data.SysCreate = DateTime.Now;
                data.SysLastUpdBy = user;
                data.SysLastUpd = DateTime.Now;
                data.SysDeleted = false;
                object obj = data.Insert();
                if (obj != null)
                {
                    res.code = HttpCode.success;
                    res.message = "添加成功";
                }
                else
                {
                    res.code = HttpCode.Add_Failed;
                    res.message = "添加失败";
                }

            }
            catch (Exception ex)
            {
                MessageBL.Insert(new MessageBL( "account", "添加账户错误：" + ex.Message));
                res.code = HttpCode.fail;
                res.message = ex.Message;
            }
            return res;

        }



       /// <summary>
        /// 获取用户列表
       /// </summary>
       /// <param name="page">页数</param>
       /// <param name="pagesize">每页行数</param>
       /// <param name="name">姓名</param>
       /// <param name="order">排序方式</param>
        /// <param name="sort">排序字段</param>
       /// <returns></returns>
        [HttpGet]
        [Route("list")]
        [HMACAuthenticationAttribute]
        public ApiResult getAccountList(long page, long pagesize,string name,string order,string sort)
        { 
            ApiResult res = new ApiResult();

            try
            {
                string sqlwhere = "";
                if (!string.IsNullOrWhiteSpace(name))
                {
                    sqlwhere = string.Format(@" and Name like '%{0}%' ", name);
                }
                string sql = string.Format(@"select ID,Name,SysCreate from Account  where SysDeleted=0 {0} order by {1} {2}", sqlwhere, sort, order);
                Page<object> list = db.Page<object>(page, pagesize,sql);
                res.code = HttpCode.success;
                res.message = "获取用户列表成功";
                res.data = list;
            }
            catch (Exception ex)
            {
                MessageBL.Insert(new MessageBL("account", "获取用户列表错误：" + ex.Message));
                res.code = HttpCode.fail;
                res.message = ex.Message;
            }
            return res;

        }

    }
}